package com.wsg.dep.buffer;

import com.wsg.dep.core.Cursored;
import com.wsg.dep.core.event.EventFactory;
import com.wsg.dep.core.event.EventSequencer;
import com.wsg.dep.exception.InsufficientCapacityException;
import com.wsg.dep.seq.Sequence;
import com.wsg.dep.seq.Sequencer;

public class RingBuffer<E> extends RingBufferFields<E> implements Cursored, EventSequencer<E> {

    /**
     * 初始化游标的值
     */
    public static final long INITIAL_CURSOR_VALUE = Sequence.INITIAL_VALUE;

    /**
     * cache_line的填充，减少伪共享命中
     */
    protected long p1, p2, p3, p4, p5, p6, p7;

    /**
     * 构造器
     *
     * @param eventFactory 事件工厂
     * @param sequencer    序列化器
     */
    private RingBuffer(EventFactory<E> eventFactory, Sequencer sequencer) {
        super(eventFactory, sequencer);
    }

    /**
     * 获取游标
     * @return
     */
    @Override
    public long getCursor() {
        return sequencer.getCursor();
    }

    /**
     * 获取环形队列中存储的事件
     * @param sequence
     * @return
     */
    @Override
    public E get(long sequence) {
        // 从环形队列中定位指定序列的元素
        return elementAt(sequence);
    }

    /**
     * 获取环形队列的大小
     * @return
     */
    @Override
    public int getBufferSize() {
        // 在构造函数中初始化
        return bufferSize;
    }

    /**
     * 用于检查是否有足够的可用容量来容纳指定数量的事件
     * 从序列化管理器中获取
     * @param sequence
     * @return
     */
    @Override
    public boolean hasAvailableCapacity(int sequence) {
        return sequencer.hasAvailableCapacity(sequence);
    }

    /**
     * 剩余可用容量
     * @return
     */
    @Override
    public long remainingCapacity() {
        return sequencer.remainingCapacity();
    }

    /**
     * 下一个序列
     * @return
     */
    @Override
    public long next() {
        return sequencer.next();
    }

    /**
     * 指定位置的下一个序列
     * @param sequence
     * @return
     */
    @Override
    public long next(int sequence) {
        return sequencer.next(sequence);
    }

    /**
     * 尝试获取下一个
     * @return
     * @throws InsufficientCapacityException
     */
    @Override
    public long tryNext() throws InsufficientCapacityException {
        return sequencer.tryNext();
    }

    /**
     * 尝试获取指定位置的下一个
     * @param sequence
     * @return
     * @throws InsufficientCapacityException
     */
    @Override
    public long tryNext(int sequence) throws InsufficientCapacityException {
        return sequencer.tryNext(sequence);
    }

    /**
     * 发布指定序号的事件
     * @param sequence
     */
    @Override
    public void publish(long sequence) {
        sequencer.publish(sequence);
    }

    /**
     * 发布从 lower 到 upper 序号范围的事件
     * @param lower
     * @param upper
     */
    @Override
    public void publish(long lower, long upper) {
        sequencer.publish(lower, upper);
    }
}
